package com.lujianfei.netease_android_shareelement.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
import com.lujianfei.netease_android_shareelement.R
import com.lujianfei.netease_android_shareelement.beans.ListEntity

class ShareElementAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val list = arrayListOf<ListEntity>()
    var onClickListener: ((View, Int) -> Unit)? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflate = LayoutInflater.from(parent.context).inflate(R.layout.adapter_share_element, parent, false)
        return MyViewHolder(inflate)
    }

    override fun getItemCount(): Int = list.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is MyViewHolder) {
            val entity = list[holder.adapterPosition]
            holder.setIcon(entity.icon)
            holder.setTitle(entity.title)
            // 设置 TransitionName
            ViewCompat.setTransitionName(holder.getIcon(), holder.itemView.context.getString(R.string.transition_name_icon) + "_" + holder.adapterPosition)
            ViewCompat.setTransitionName(holder.getTitle(), holder.itemView.context.getString(R.string.transition_name_title) + "_" + holder.adapterPosition)
        }
        holder.itemView.setOnClickListener {
            onClickListener?.invoke(holder.itemView, holder.adapterPosition)
        }
    }

    fun setData(data: List<ListEntity>) {
        list.clear()
        list.addAll(data)
        notifyDataSetChanged()
    }

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun setIcon(resId: Int) {
            val icon = itemView.findViewById<ImageView>(R.id.icon)
            icon.setImageResource(resId)
        }

        fun setTitle(titleText: String) {
            val title = itemView.findViewById<TextView>(R.id.title)
            title.text = titleText
        }

        fun getIcon(): ImageView {
            return itemView.findViewById<ImageView>(R.id.icon)
        }

        fun getTitle(): TextView {
            return itemView.findViewById<TextView>(R.id.title)
        }
    }
}